package com.tarena.demo.luban.all.main.consumer;

import com.tarena.demo.luban.all.main.service.OrderService;
import com.tarena.demo.luban.commons.exception.BusinessDemoException;
import com.tarena.demo.luban.protocol.order.param.OrderAddParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 新增订单的consumer
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "order-topic",consumerGroup = "order-consumer")
public class OrderAddConsumer implements RocketMQListener<OrderAddParam> {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(OrderAddParam orderAddParam) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        //定义锁的key
        String lockKey = "luban:demo:order:add:" + orderAddParam.getOrderSn()+".lock";
        //生成一个当前业务的随机值
        String rdValue = new Random().nextInt(9999)+"";
        try {
            //消费开始
            //1.抢锁，成功时会超时10s
            Boolean result = opsForValue.setIfAbsent(lockKey,rdValue,10, TimeUnit.SECONDS);
            //2.抢锁失败，等待5s重新抢锁
            while (!Boolean.TRUE.equals(result)){
                Thread.sleep(5000);
                result = opsForValue.setIfAbsent(lockKey,rdValue,10, TimeUnit.SECONDS);
            }
            //3.抢锁成功，执行业务
            orderService.addOrder(orderAddParam);
        } catch (BusinessDemoException e) {
            log.error("新增订单失败",e);
        } catch (InterruptedException e){
            log.error("新增订单失败",e);
        } catch (Throwable t) {
            log.error("新增订单失败",t);
            throw t;
        } finally {
            //手动释放锁，避免固定超时时间，提高效率
            //todo ver4:使用lua脚本释放锁，保证先查后删的逻辑是原子级的
            String lock = opsForValue.get(lockKey);
            if (rdValue.equals(lock)){
                stringRedisTemplate.delete(lockKey);
            }
        }
        log.info("新增订单成功");
    }
}
